﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;

namespace IpConfigWin
{
   
    public partial class Form1 : Form
    {
         private const int BAUD = 115200;

        //Used to index the IPAddresList which contains both IPv4 and IPv6 addresses
        int count = 0;

        public Form1()
        {
            InitializeComponent();

            //Defaults (No HS etc) OK.
            StreamDriverPort1.BaudRate = BAUD;

            count = 0;

            //Autopdisplay and send IPAddress (IPv4)
            DoIP();
        }



        //Press button to toggle between IPv4 and IPv6 addresses
        private void button1_Click(object sender, EventArgs e)
        {
            DoIP();
        }

        private void DoIP()
        {
            string host = Dns.GetHostName();
            IPHostEntry ip = Dns.GetHostEntry(host);

            //In case this list changes, eg Plugin USB NIC
            if (count > ip.AddressList.Count() - 1)
                count = 0;
            //Get next index, downlwards
            count--;
            //Restart if last did [0]
            if (count == -1)
                count = ip.AddressList.Count() - 1;
            //Address zero is IPv6, address 1 is ipv4, hence start from end of list
            string ipaddr = ip.AddressList[count].ToString();

            //Write to label
            label1.Text = ipaddr;

            //Send IPAddress to COM1
            if (!StreamDriverPort1.IsOpen)
                StreamDriverPort1.Open();
            if (StreamDriverPort1.IsOpen)
            {
                string message = "\r\n IPAddress = " +ipaddr+ "\r\n";
                StreamDriverPort1.WriteLine(message);
            }
        }


        private void button2_Click(object sender, EventArgs e)
        {
            if (StreamDriverPort1.IsOpen)
                StreamDriverPort1.Close();
            Application.Exit();
        }

        private void label1_ParentChanged(object sender, EventArgs e)
        {

        }
    }
}
